﻿using System.Windows.Controls;
using CCF20Model;
using WiseLinkWPF.Windows.Controls.GridView;
using System.Collections;
using System.Windows;
using WiseLinkWPF.Windows.Controls;
using System.Collections.Generic;
using System.Windows.Data;
using WiseLinkWPF.Windows.Data;
using System.ComponentModel;
using System;
using CCF20.Shared;
using WiseLink.RDS.Resource;

namespace CCF20Module
{
    /// <summary>
    /// Interaction logic for CustomizeMaintenance.xaml
    /// </summary>
    public partial class CustomizeMaintenance
    {
        public static readonly DependencyProperty TableNameProperty = DependencyProperty.Register("TableName", typeof(string), typeof(CustomizeMaintenance), null);
        public string TableName
        {
            get
            {
                return (string)GetValue(TableNameProperty);
            }

            set
            {
                SetValue(TableNameProperty, value);
            }
        }
        public CustomizeMaintenance()
        {
            InitializeComponent();
            
        }

        
        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            ListHelp listHelp = new ListHelp();
            switch (TableName)
            {
                case "VehicleType":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetVehicleType();
                    this.New.IsEnabled = false;
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForVehicleType());
                    break;
                
                case "MaintenanceType":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetMaintenanceType();
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForMaintenanceType());
                    break;
                case "SMSTemplate":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetSMSTemplate(true);
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForSMSTemplate());
                    break;
                case "CustomizedTroubleCode":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetCustomizedTroubleCode();
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForCustomizedTroubleCode());
                    break;
                case "RemindList":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetRemindList();
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForRemindList());
                    break;
                case "SMSHistory":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetSMSHistory();
                    this.New.IsEnabled = false;
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForSMSHistory());
                    break;
                case "TroubleDevice":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetTroubledDevice();
                    this.New.IsEnabled = false;
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForTroubleDevice());
                    break;

                case "ManagerReportReceiver":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetManagerReportReceiver();
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForManagerReportReceiver());
                    break;

                case "WiseLinkIDS":
                    this.radMaintenanceRecord.ItemsSource = customizeModel.GetWiseLinkIDS();
                    AddColumnToGrid(this.radMaintenanceRecord, listHelp.GetColumnForIDS());
                    break;
                
                
            }
            ApplyResourceToGrid();
            ApplyResourceToButton();
        }
        private void AddColumnToGrid(RadGridView grid, List<GridColumn> columnList)
        {
            foreach (GridColumn column in columnList)
            {
                if ((this.TableName == "MaintenanceType" || this.TableName == "CustomizedTroubleCode") && column.Binding.Contains("VehicleTypeID"))
                {
                    GridViewComboBoxColumn comboColumn = new GridViewComboBoxColumn();
                    comboColumn.ItemTemplate = (DataTemplate)this.FindResource("VehicleTypeLookupTemplate");
                    comboColumn.ItemsSource = customizeModel.GetVehicleType();
                    comboColumn.DataMemberBinding = new Binding("VehicleTypeID");
                    comboColumn.Header = column.Header;
                    comboColumn.UniqueName = column.Header;
                    comboColumn.SelectedValueMemberPath = "VehicleTypeID";
                    comboColumn.IsFilterable = false;
                    comboColumn.IsReadOnly = true;
                    comboColumn.Name = column.Binding.GetColumnName();
                    comboColumn.Header = WiseLink.RDS.Resource.CustomerTableString.ResourceManager.GetString("VehicleType");
                    grid.Columns.Add(comboColumn);
                }
                else if (this.TableName == "CustomizedTroubleCode" && column.Binding.Contains("CodeDescription"))
                {
                    GridViewDataColumn codeDescriptionColumn = new GridViewDataColumn();
                    codeDescriptionColumn.DataMemberBinding = new Binding(column.Binding);
                    codeDescriptionColumn.CellTemplate = (DataTemplate)this.FindResource("CodeDescriptionTemplate");
                    codeDescriptionColumn.CellEditTemplate = (DataTemplate)this.FindResource("CodeDescriptionEditTemplate");
                    codeDescriptionColumn.Header = column.Header;
                    codeDescriptionColumn.UniqueName = column.Header;
                    codeDescriptionColumn.IsReadOnly = column.IsReadOnly;
                    codeDescriptionColumn.Name = column.Binding.GetColumnName();
                    grid.Columns.Add(codeDescriptionColumn);
                }
                else if (this.TableName == "SMSTemplate" && column.Binding == "SMSText")
                {
                    GridViewDataColumn smstextColumn = new GridViewDataColumn();
                    smstextColumn.DataMemberBinding = new Binding(column.Binding);
                    smstextColumn.TextTrimming = TextTrimming.CharacterEllipsis;
                    smstextColumn.TextWrapping = TextWrapping.Wrap;
                    smstextColumn.CellEditTemplate = (DataTemplate)this.FindResource("SMSContentEditTemplate");
                    smstextColumn.Header = column.Header;
                    smstextColumn.UniqueName = column.Header;
                    smstextColumn.IsReadOnly = column.IsReadOnly;
                    smstextColumn.MaxWidth = 450;
                    smstextColumn.Name = column.Binding.GetColumnName();
                    grid.Columns.Add(smstextColumn);

                }
                else if (this.TableName == "SMSTemplate" && column.Binding == "SMSType") 
                {
                    GridViewDataColumn smstypeColumn = new GridViewDataColumn();
                    smstypeColumn.DataMemberBinding = new Binding(column.Binding);
                    smstypeColumn.DataMemberBinding.Mode = BindingMode.TwoWay;
                    smstypeColumn.CellStyleSelector = (StyleSelector)this.FindResource("smstypeStyle");
                    smstypeColumn.CellEditTemplate = (DataTemplate)this.FindResource("SMSTypeComboBox");
                    smstypeColumn.Header = column.Header;
                    smstypeColumn.UniqueName = column.Header;
                    smstypeColumn.IsReadOnly = column.IsReadOnly;
                    smstypeColumn.Name = column.Binding.GetColumnName();
                    grid.Columns.Add(smstypeColumn);

                }
                else
                {
                    GridViewDataColumn newcolumn = new GridViewDataColumn();
                    newcolumn.DataMemberBinding = new Binding(column.Binding);
                    newcolumn.Header = column.Header;
                    newcolumn.UniqueName = column.Header;
                    newcolumn.TextTrimming = TextTrimming.CharacterEllipsis;
                    newcolumn.TextWrapping = TextWrapping.Wrap;
                    newcolumn.MaxWidth = 600;
                    newcolumn.IsReadOnly = column.IsReadOnly;
                    newcolumn.Name = column.Binding.GetColumnName();
                    grid.Columns.Add(newcolumn);
                }
            }
        }
        private void radMaintenanceRecord_RowEditEnded(object sender, WiseLinkWPF.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {


            if (e.EditAction == GridViewEditAction.Commit)
            {

                if (this.TableName == "VehicleType")
                {
                    VehicleType vt = (VehicleType)e.EditedItem;
                    if (    (vt == null) ||
                            string.IsNullOrEmpty(vt.Manufacture) ||
                            string.IsNullOrEmpty(vt.Model) ||
                            string.IsNullOrEmpty(vt.EngineType) ||
                            string.IsNullOrEmpty(vt.Displacement))
                    {
                        e.Row.CancelEdit();
                        if (vt != null)
                        {
                            ((IList)radMaintenanceRecord.ItemsSource).Remove(vt);
                        }
                        return;
                    }
                }
                else if (this.TableName == "MaintenanceType")
                {
                    this.radMaintenanceRecord.Columns["车型"].IsReadOnly = true;
                    this.radMaintenanceRecord.Columns["项目描述"].IsReadOnly = true;
                    MaintenanceType mt = (MaintenanceType)e.EditedItem;
                    if ( mt == null ||
                         mt.VehicleTypeID == null ||
                         mt.ServiceMileage == null ||
                         mt.ServicePeriod == null ||
                         mt.Priority == null)   
                    {
                        e.Row.CancelEdit();
                        if (mt != null)
                        {
                            ((IList)radMaintenanceRecord.ItemsSource).Remove(mt);
                        }
                        return;
                    }
                }
                else if (this.TableName == "SMSTemplate")
                {
                    SMSTemplate template = (SMSTemplate)e.EditedItem;
                    if ( string.IsNullOrEmpty(template.SMSType) || string.IsNullOrEmpty(template.SMSTitle) || string.IsNullOrEmpty(template.SMSText))
                    {
                        Utility.ShowMessageBox(Message.SMSTemplate_Cant_Empty);
                        radMaintenanceRecord.CancelEdit();
                        return;
                    }
                    if ((string)e.OldValues["SMSType"] != template.SMSType)
                    {
                        template.IsMonthly = false;
                    }
                    template.SMSType = template.SMSType.Replace("WiseLinkWPF.Windows.Controls.RadComboBoxItem:", string.Empty).Trim();
                }
                else if (this.TableName == "CustomizedTroubleCode")
                {
                    this.radMaintenanceRecord.Columns["车型"].IsReadOnly = true;
                    this.radMaintenanceRecord.Columns["故障号"].IsReadOnly = true;
                    this.radMaintenanceRecord.Columns["故障号版本"].IsReadOnly = true;
                }

                

                customizeModel.Update();
                this.radMaintenanceRecord.ScrollIntoView(this.radMaintenanceRecord.Items[0]);
                this.radMaintenanceRecord.ScrollIntoView(this.radMaintenanceRecord.CurrentItem);
                //SortDescriptor descriptor = new SortDescriptor();
                //descriptor.Member = this.TableName+"ID";
                //descriptor.SortDirection = ListSortDirection.Descending;
                //this.radMaintenanceRecord.SortDescriptors.Clear();
                //this.radMaintenanceRecord.SortDescriptors.Add(descriptor);
            }
        
            //Refresh_Click(null, null);
        }
        private void RadContextMenu_ItemClick(object sender, WiseLinkWPF.Windows.RadRoutedEventArgs e)
        {
            RadContextMenu menu = (RadContextMenu)sender;
            RadMenuItem clickedItem = e.OriginalSource as RadMenuItem;
            GridViewRow row = menu.GetClickedElement<GridViewRow>();

            //radMaintenanceRecord.SelectedItem = row;
            if (clickedItem != null && row != null)
            {
                string header = clickedItem.Name;

                if (header == "btnDelete")
                {

                    if (this.TableName == "SMSTemplate")
                    {
                        SMSTemplate st = (SMSTemplate)row.DataContext;
                        if (st.IsSystem)
                        {
                            Utility.ShowMessageBox(Message.SMSTemplate_Cant_Delete);
                            return;
                        }
                    }
                    else if (this.TableName == "CustomizedTroubleCode")
                    {
                        CustomizedTroubleCode code = (CustomizedTroubleCode)row.DataContext;
                        if (code.OperationType == "人工排除")
                        {
                            //取消人工排除的偶发故障
                            customizeModel.RemoveCustomizedTroubleCode(code.Code, code.CodeVersion, code.VehicleTypeID);
                        }
                        else
                        {
                            customizeModel.RemoveDirectCode(code.Code, code.CodeVersion, code.VehicleTypeID);
                            //取消直通车

                        }
                    }
                    ((IList)this.radMaintenanceRecord.ItemsSource).Remove(row.Item);
                    customizeModel.Update();
                    //this.radMaintenanceRecord.Rebind();

                }
                else if (header == "btnCopy")
                {

                    switch (TableName)
                    {
                        case "MaintenanceType":
                            MaintenanceType mt = row.Item as MaintenanceType;
                            MaintenanceType newMT = new MaintenanceType();
                            newMT.Name = mt.Name;
                            newMT.ServiceMileage = mt.ServiceMileage;
                            newMT.ServicePeriod = mt.ServicePeriod;
                            newMT.VehicleTypeID = mt.VehicleTypeID;
                            newMT.Priority = customizeModel.SetMaintenancePriority(mt.VehicleTypeID, mt.Name);
                            newMT.TyID = mt.TyID;
                            newMT.AnchiID = mt.AnchiID;
                            ((IList)this.radMaintenanceRecord.ItemsSource).Add(newMT);
                            customizeModel.Update();
                            this.radDataPagerMaintenanceRecord.MoveToLastPage();
                            this.radMaintenanceRecord.Items.MoveCurrentToLast();
                            break;
                        default:
                            return;
                    }
                }
                else if (header == "btnConfirmFault")
                {
                    TroubledDevice troubleDevice = row.Item as TroubledDevice;
                    
                    troubleDevice.Device.IsDefected = true;
                    ((IList)this.radMaintenanceRecord.ItemsSource).Remove(troubleDevice);
                    customizeModel.Update();
                }
                else if (header == "btnMonthlyReport")
                {
                    SMSTemplate smsTemplate = row.Item as SMSTemplate;
                    if (smsTemplate.SMSType == "月度报告" || smsTemplate.SMSType == "管理")
                    {
                        smsTemplate.IsMonthly = !smsTemplate.IsMonthly;
                        customizeModel.Update();
                        this.radMaintenanceRecord.Rebind();
                    }
                }

            }
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {

            Button btn = (Button)sender;
            
            //CCFZIC ccfZIC;
            if (btn.Name == "Refresh")
            {
                switch (TableName)
                {
                    case "WiseLinkIDS":
                        eRDSZIC.GetWiseLinkIDS();
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetWiseLinkIDS();
                        break;
                    case "VehicleType":
                        eRDSZIC.GetVehicleType();
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetVehicleType();
                        break;

                    case "MaintenanceType":
                        
                        eRDSZIC.GetMaintenanceType();
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetMaintenanceType();

                        break;
                    case "SMSTemplate":
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetSMSTemplate(true);

                        break;
                    case "CustomizedTroubleCode":
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetCustomizedTroubleCode();

                        break;
                    case "RemindList":
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetRemindList();

                        break;
                    case "SMSHistory":
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetSMSHistory();
                        break;
                    case "TroubleDevice":
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetTroubledDevice();
                        break;
                    case "ManagerReportReceiver":
                        this.radMaintenanceRecord.ItemsSource = customizeModel.GetManagerReportReceiver();
                        break;
                }
                this.Dispatcher.BeginInvoke(new Action(() => this.radMaintenanceRecord.Rebind()));
            }
            else
            {


                

                foreach (GridViewBoundColumnBase column in radMaintenanceRecord.Columns)
                {
                    if (column.IsFilterable)
                    {
                        for (int i = 0; i < column.DataControl.FilterDescriptors.Count; i++)
                        {
                            column.DataControl.FilterDescriptors.RemoveAt(0);
                        }
                        //string dataMember = column.DataMemberBinding.Path.Path;
                        //FilterDescriptor nullFilter = new WiseLinkWPF.Windows.Data.FilterDescriptor(dataMember
                        //                                                , WiseLinkWPF.Windows.Data.FilterOperator.IsEqualTo
                        //                                                , null);
                        //CompositeFilterDescriptor compositeFilter = new CompositeFilterDescriptor();
                        //compositeFilter.FilterDescriptors.Add(nullFilter);
                        //compositeFilter.FilterDescriptors.Add(column.DataControl.FilterDescriptors[0]);
                        //column.DataControl.FilterDescriptors.Add(compositeFilter);
                    }
                }
                switch (TableName)
                {
                    case "VehicleType":
                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new VehicleType());
                        break;

                    case "MaintenanceType":
                        this.radMaintenanceRecord.Columns["车型"].IsReadOnly = false;
                        this.radMaintenanceRecord.Columns["项目描述"].IsReadOnly = false;

                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new MaintenanceType());
                        break;
                    case "SMSTemplate":
                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new SMSTemplate());

                        break;
                    case "CustomizedTroubleCode":
                        this.radMaintenanceRecord.Columns["车型"].IsReadOnly = false;
                        this.radMaintenanceRecord.Columns["故障号"].IsReadOnly = false;
                        this.radMaintenanceRecord.Columns["故障号版本"].IsReadOnly = false;
                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new CustomizedTroubleCode());
                        break;
                    case "RemindList":
                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new RemindList());
                        break;
                    case "SMSHistory":
                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new SMSHistory());
                        break;
                    case "ManagerReportReceiver":
                        ((IList)this.radMaintenanceRecord.ItemsSource).Add(new ManagerReportReceiver());
                        break;
                }
                this.radDataPagerMaintenanceRecord.MoveToLastPage();
                this.radMaintenanceRecord.Items.MoveCurrentToLast();

                this.radMaintenanceRecord.ScrollIntoView(this.radMaintenanceRecord.CurrentItem);
                
            }
        }

        private void RadContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            RadContextMenu menu = (RadContextMenu)sender;

            //0-删除 1-复制 2-确认故障,选择/取消月度报告
            switch (TableName)
            {
                case "SMSTemplate":
                    ((RadMenuItem)menu.Items[0]).IsEnabled = true;
                    ((RadMenuItem)menu.Items[1]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[2]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[3]).IsEnabled = true;
                    break;
                
                case "MaintenanceType":
                    ((RadMenuItem)menu.Items[0]).IsEnabled = true;
                    ((RadMenuItem)menu.Items[1]).IsEnabled = true;
                    ((RadMenuItem)menu.Items[2]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[3]).IsEnabled = false;
                    break;
                case "VehicleType":
                    ((RadMenuItem)menu.Items[0]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[1]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[2]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[3]).IsEnabled = false;
                    break;
                
                case "TroubleDevice":
                    ((RadMenuItem)menu.Items[0]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[1]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[2]).IsEnabled = true;
                    ((RadMenuItem)menu.Items[3]).IsEnabled = false;

                    break;
                default:
                    ((RadMenuItem)menu.Items[0]).IsEnabled = true;
                    ((RadMenuItem)menu.Items[1]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[2]).IsEnabled = false;
                    ((RadMenuItem)menu.Items[3]).IsEnabled = false;
                    break;
            }
            
        }

        private void radMaintenanceRecord_CellValidating(object sender, GridViewCellValidatingEventArgs e)
        {
            if (e.NewValue == e.OldValue) return;
            
            GridViewCell cell = e.Cell;
            GridViewRow row = (GridViewRow)e.Cell.ParentRow;
            string validationText = string.Empty;
            GridViewEditorPresenter viewPresenter = cell.Content as GridViewEditorPresenter;
            if (viewPresenter != null)
            {

                // for maintenancetype, it could be combobox.
                TextBox cellTextBox = viewPresenter.Content as TextBox;
                RadComboBox smstypeComboBox = viewPresenter.Content as RadComboBox;

                switch (TableName)
                {
                    case "SMSTemplate":
                        if (smstypeComboBox != null && smstypeComboBox.SelectedValue != null)
                        {
                            SMSTemplate template = (SMSTemplate)row.DataContext;
                            template.SMSType = template.SMSType.Replace("WiseLinkWPF.Windows.Controls.RadComboBoxItem:", string.Empty).Trim();
                        }
                        break;

                    case "VehicleType":
                        if (cellTextBox != null && string.IsNullOrEmpty(cellTextBox.Text))
                        {
                            validationText = string.Concat(cell.Column.UniqueName, "不可以为空");
                        }
                        break;
                    case "MaintenanceType":

                        switch (cell.Column.UniqueName)
                        {

                            case "项目描述":

                                MaintenanceType mt = (MaintenanceType)row.DataContext;
                                mt.Priority = customizeModel.SetMaintenancePriority(mt.VehicleTypeID, (string)e.NewValue);
                                break;
                            default:
                                break;
                        }
                        break;
                }
                if (!string.IsNullOrEmpty(validationText))
                {
                    ToolTipService.SetToolTip(cell, validationText);
                    e.IsValid = false;
                    e.ErrorMessage = validationText;

                }
            }
        }

       
    }
}
